﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;

using GroundWater.Data;
using GroundWater.BusinessActions;

using MonitoringTable = GroundWater.Data.MonitoringDataSet.MonitoringDataTable;
using MonitoringRow = GroundWater.Data.MonitoringDataSet.MonitoringRow;

using WellTable = GroundWater.Data.InfoDataSet.WellsDataTable;
using WellRow = GroundWater.Data.InfoDataSet.WellsRow;

namespace GroundWater.waterlevel
{
    public partial class WaterlevelUpdate1 : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SiteUtil.Validate(this, "监测数据录入");
            if (!this.IsPostBack)
            {
                txtStartDate.Value = DateTime.Now.ToString("yyyy-MM-dd");
                txtEndDate.Value = DateTime.Now.ToString("yyyy-MM-dd");

                WellTable wells = Well.GetAll(false, true);

                if (wells == null || wells.Count == 0)
                {
                    gvMonitoring.Visible = false;
                    RegisterClientScript("alert('还没有水井信息，请先输入');", lblJavaScript);
                }
            }
            //Monitoring.GetPaged(1, 1);
        }

        protected void RowDataBound(object sender, GridViewRowEventArgs args)
        {
            GridView gridView = (GridView)sender;

            if (gridView.SortExpression.Length > 0)
            {
                int cellIndex = -1;
                foreach (DataControlField field in gridView.Columns)
                {
                    if (field.SortExpression == gridView.SortExpression)
                    {
                        cellIndex = gridView.Columns.IndexOf(field);
                        break;
                    }
                }

                if (cellIndex > -1)
                {
                    if (args.Row.RowType == DataControlRowType.Header)
                    {
                        //  this is a header row,
                        //  set the sort style
                        args.Row.Cells[cellIndex].CssClass +=
                            (gridView.SortDirection == SortDirection.Ascending
                            ? " sortasc" : " sortdesc");
                    }
                }
            }

            if (args.Row.RowType == DataControlRowType.DataRow)
            {
                if (args.Row.RowIndex > -1)
                {
                    if (args.Row.Cells[8].Controls.Count > 0)
                    {
                        LinkButton btnDelete = args.Row.Cells[8].Controls[0] as LinkButton;
                        if (btnDelete != null && btnDelete.Text == "删除")
                        {
                            btnDelete.OnClientClick = "return confirm('您是否确认删除此项？');";
                        }
                    }
                }
            }
        }

        protected void odsMonitoring_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
        {

        }

        protected void gvMonitoring_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            //string wellCode = drpWell.SelectedValue;
            //string startDate = txtStartDate.Value;
            //string endDate = txtEndDate.Value;

            //updPanel.Update();
            gvMonitoring.PageIndex = 0;
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (drpWell.SelectedItem != null)
            {
                MonitoringTable dt = Monitoring.FetchPaged(drpWell.SelectedItem.Value, txtStartDate.Value, txtEndDate.Value, "", 1000000, 0);
                ExportToExcel(drpWell.SelectedItem.Text + ".xls", dt, gvMonitoring);
            }
        }



        public void ExportToExcel(string fileName, DataTable dt, GridView gv)
        {
            this.Page.Response.Clear();
            this.Page.Response.Buffer = true;
            this.Page.Response.AddHeader("Content-type", "application/x-msdownload");
            this.Page.Response.ContentType = "application/vnd.ms-excel";
            this.Page.Response.Charset = "utf-8";
            this.Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            this.Page.Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + "\"");
            this.EnableViewState = false;

            System.IO.StringWriter sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            GridView grid = new GridView();

            grid.RowDataBound += new GridViewRowEventHandler(gvExport_RowDataBound);
            grid.DataSource = dt;
            grid.AutoGenerateColumns = false;
            grid.Columns.Clear();
            foreach (DataControlField col in gv.Columns)
            {
                if (col is ButtonField || col is CommandField)
                {
                    continue;
                }
                if (col is BoundField || col is TemplateField || col is CheckBoxField)
                {
                    grid.Columns.Add(col);
                }
                if (col is HyperLinkField)
                {
                    BoundField field = new BoundField();
                    field.DataField = ((HyperLinkField)col).DataTextField;
                    field.HeaderText = col.HeaderText;
                    grid.Columns.Add(field);
                }
            }

            grid.DataBind();
            grid.RenderControl(htw);

            this.Page.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
            this.Page.Response.Write(@"<style> .text { mso-number-format:\@; } </style> "); ;
            //string fileName = HttpUtility.UrlEncode(ExcelFileName + ".xls", Encoding.GetEncoding("GB2312"));
            //HttpContext.Current.Response.AddHeader("content-disposition","attachment;filename=" + fileName);
            this.Page.Response.Write(sw.ToString());
            this.Page.Response.End();
        }

        protected void gvExport_RowDataBound(object sender, GridViewRowEventArgs args)
        {
            if (args.Row.RowType == DataControlRowType.DataRow)
            {
                args.Row.Cells[4].Attributes.Add("class", "text");
            }
        }

        bool triggered = false;
        protected void drpWell_SelectedIndexChanged(object sender, EventArgs e)
        {
            ////btnAdd_Click(null, e);
            //if (drpWells.SelectedValue != null)
            //{
            //    txtCode.Text = drpWells.SelectedValue;
            //    WellRow well = GroundWater.BusinessActions.Well.GetById(txtCode.Text, false);
            //    txtSectionPlane.Text = well.SectionPlane;
            //    txtSIMCard.Text = well.SIMCard;
            //    txtBTUAddress.Text = well.BTUAddress;
            //    //scriptManager.RegisterDataItem(txtCode, drpWells.SelectedValue + "|" + well.SectionPlane + "|" + well.SIMCard + "|" + well.BTUAddress);
            //}

            //SetDisable();
            //mdlPopup.Hide();
            //updPnl.Update();

            //triggered = true;
        }

        //protected void drpWells_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    if (triggered)
        //    {

        //        return;
        //    }
        //    //btnAdd_Click(null, e);
        //    if (drpWells.SelectedValue != null)
        //    {
        //        txtCode.Text = drpWells.SelectedValue;
        //        WellRow well = GroundWater.BusinessActions.Well.GetById(txtCode.Text, false);
        //        txtSectionPlane.Text = well.SectionPlane;
        //        txtSIMCard.Text = well.SIMCard;
        //        txtBTUAddress.Text = well.BTUAddress;
        //        //scriptManager.RegisterDataItem(txtCode, drpWells.SelectedValue + "|" + well.SectionPlane + "|" + well.SIMCard + "|" + well.BTUAddress);
        //    }

        //    SetDisable();
        //    mdlPopup.Show();
        //}

        protected void ods_Deleting(object sender, ObjectDataSourceMethodEventArgs e)
        {
            //e.InputParameters["id"] = e.InputParameters["Code"];
            //e.InputParameters.Remove("Code");
            //e.InputParameters["wellCode"] = e.InputParameters["WellCode"];
            //e.InputParameters.Remove("WellCode");


            //e.InputParameters["monitoringTime"] = e.InputParameters["MonitorTime"];
            //e.InputParameters.Remove("MonitorTime");

            e.InputParameters.Remove("WellCode");
            e.InputParameters.Remove("MonitorTime");


            e.InputParameters["Id"] = new Guid((Byte[])e.InputParameters["Id"]);
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            ClearFields();
            GridViewRow row = ((LinkButton)sender).Parent.Parent as GridViewRow;

            string wellCode = this.gvMonitoring.DataKeys[row.RowIndex].Value.ToString();
            string monitorTime = this.gvMonitoring.DataKeys[row.RowIndex].Values[1].ToString();
            Guid id = new Guid((Byte[])this.gvMonitoring.DataKeys[row.RowIndex].Values[2]);

            //drpWells.SelectedValue = drpWell.SelectedValue;
            //if (!string.IsNullOrEmpty(id))
            //{
            //    SetFields(id);
            //}
            SetFields(id);

            updPnl.Update();
            //SetDisable();
            mdlPopup.Show();
        }

        private void SetFields(Guid id)
        {
            MonitoringRow row = GroundWater.BusinessActions.Monitoring.GetById(id, false);

            txtCode.Text = row.WellCode;
            txtName.Text = row.WellName;
            //drpWells.SelectedValue = row.WellName;
            txtMonitorTime.Text = row.MonitorTime.ToString("yyyy-MM-dd HH:mm");
            txtWaterlevel.Text = row.Waterlevel.ToString();
            if (!row.IsCellVoltageNull())
            {
                txtCellVoltage.Text = row.CellVoltage;
            }
            if (!row.IsFlowRateNull())
            {
                txtFlowRate.Text = row.FlowRate.ToString();
            }

            if (!row.IsHydraulicPressureNull())
            {
                txtHydraulicPressure.Text = row.HydraulicPressure.ToString();
            }

            if (!row.IsOriginalWaterLevelNull())
            {
                txtOriginalWaterLevel.Text = row.OriginalWaterLevel;
            }
            if (!row.IsWaterQualityNull())
            {
                txtWaterQuality.Text = row.WaterQuality;
            }
            if (!row.IsSectionPlaneNull())
            {
                txtSectionPlane.Text = row.SectionPlane;
            }
            if (!row.IsSIMCardNull())
            {
                txtSIMCard.Text = row.SIMCard;
            }

            if (!row.IsSIMCardNull())
            {
                txtBTUAddress.Text = row.BTUAddress;
            }


            //this.ViewState["WellCode"] = wellCode;
            //this.ViewState["MonitorTime"] = monitorTime;
            this.hidMonitorTime.Value = row.MonitorTime.ToString();
            this.hidWellCode.Value = row.WellCode;
            this.hiddenId.Value = id.ToString();

            WellRow well = GroundWater.BusinessActions.Well.GetById(row.WellCode, false);
            this.hidAltitude.Value = well.Depth.ToString();

            SetDisable();
        }

        private void SetFields(string wellCode, string monitorTime)
        {
            if (!string.IsNullOrEmpty(wellCode))
            {
                MonitoringRow row = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, DateTime.Parse(monitorTime));

                //MonitoringRow row = GroundWater.BusinessActions.Monitoring.GetById();

                txtCode.Text = row.WellCode;
                //txtName.Text = row.WellName;
                //drpWells.SelectedValue = row.WellName;
                txtMonitorTime.Text = row.MonitorTime.ToString("yyyy-MM-dd HH:mm");
                txtWaterlevel.Text = row.Waterlevel.ToString();
                if (!row.IsCellVoltageNull())
                {
                    txtCellVoltage.Text = row.CellVoltage;
                }
                if (!row.IsFlowRateNull())
                {
                    txtFlowRate.Text = row.FlowRate.ToString();
                }

                if (!row.IsHydraulicPressureNull())
                {
                    txtHydraulicPressure.Text = row.HydraulicPressure.ToString();
                }

                if (!row.IsOriginalWaterLevelNull())
                {
                    txtOriginalWaterLevel.Text = row.OriginalWaterLevel;
                }
                if (!row.IsWaterQualityNull())
                {
                    txtWaterQuality.Text = row.WaterQuality;
                }
                if (!row.IsSectionPlaneNull())
                {
                    txtSectionPlane.Text = row.SectionPlane;
                }
                if (!row.IsSIMCardNull())
                {
                    txtSIMCard.Text = row.SIMCard;
                }

                if (!row.IsSIMCardNull())
                {
                    txtBTUAddress.Text = row.BTUAddress;
                }


                //this.ViewState["WellCode"] = wellCode;
                //this.ViewState["MonitorTime"] = monitorTime;
                this.hidMonitorTime.Value = monitorTime;
                this.hidWellCode.Value = wellCode;

                WellRow well = GroundWater.BusinessActions.Well.GetById(wellCode, false);
                this.hidAltitude.Value = well.Depth.ToString();

            }

            SetDisable();
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            //
            if (txtCode.Text.Trim().Length == 0 || txtName.Text.Length == 0) return;
            string monitorTime = "";
            DateTime monitorTime1;
            if (!DateTime.TryParse(txtMonitorTime.Text, out monitorTime1))
            {
                scriptManager.RegisterDataItem(txtCode, "0");
                return;
            }

            if (this.hidMonitorTime.Value.Length > 0)
            {
                monitorTime = hidMonitorTime.Value;
            }
            else
            {
                monitorTime = txtMonitorTime.Text;
            }

            string wellCode = txtCode.Text;// drpWells.SelectedItem.Value;//this.ViewState["WellCode"] as String;


            MonitoringDataSet s = GetFields(wellCode);
            if (s == null)
            {
                //
                lblJavaScript.Text = "<script type=\"text/javascript\">alert('监测水井" + txtName.Text + ",监测时间为" + monitorTime + " 的监测记录已存在。');</script>";
                scriptManager.RegisterDataItem(this.txtMonitorTime, "1");
                return;
            }

            //this.ViewState.Remove("WellCode");
            //this.ViewState.Remove("MonitorTime");

            int cnt = GroundWater.BusinessActions.Monitoring.Update(s, false, true, new string[] { s.Monitoring.TableName });

            gvMonitoring.DataBind();

            updPanel.Update();


            ClearFields();

            //mdlPopup.Hide();
        }

        private void ClearFields()
        {
            txtCode.Text = "";
            //txtName.Text = "";
            txtMonitorTime.Text = "";
            txtWaterlevel.Text = "";
            txtCellVoltage.Text = "";
            txtFlowRate.Text = "";
            txtHydraulicPressure.Text = "";
            txtOriginalWaterLevel.Text = "";
            txtWaterQuality.Text = "";
            txtSectionPlane.Text = "";
            txtSIMCard.Text = "";
            txtBTUAddress.Text = "";
            //txtYearlyQuality.Text = "";
            //txtDailyQuality.Text = "";
            //txtAdministrationAgency.Text = "";
            //txtAdministration.Text = "";

        }

        private MonitoringDataSet GetFields(string wellCode)
        {
            MonitoringRow src = null;

            WellRow well = GroundWater.BusinessActions.Well.GetById(wellCode, false);

            if (this.hidMonitorTime.Value.Length == 0)//String.IsNullOrEmpty(wellCode)
            {
                //MonitoringRow row = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, DateTime.Parse(txtMonitorTime.Text));
                //if (row != null)
                //{
                //    return null;
                //}

                src = (new MonitoringDataSet()).Monitoring.NewMonitoringRow();
                //src.Id = Guid.NewGuid();
                src.Id = Guid.NewGuid().ToByteArray();
                src.WellCode = "";
                src.WellName = "";
                src.BTUAddress = "";
                src.CellVoltage = "";
                src.FlowRate = 0m;
                src.HydraulicPressure = 0m;
                src.MonitorTime = DateTime.Parse("1900-01-01");
                src.OriginalWaterLevel = "";
                src.SectionPlane = "";
                src.SIMCard = "";
                src.Waterlevel = 0m;
                src.WaterQuality = "";
            }
            else
            {
                // update

                //src = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, DateTime.Parse(monitorTime));
                string id = this.hiddenId.Value.ToString();
                src = GroundWater.BusinessActions.Monitoring.GetById(new Guid(id), false);
            }
            src.WellCode = well.Code; //txtCode.Text;
            src.WellName = well.Name;// drpWells.SelectedItem.Text;//txtName.Text;
            src.SectionPlane = well.SectionPlane;// txtSectionPlane.Text;
            src.BTUAddress = well.BTUAddress;// txtBTUAddress.Text;
            src.SIMCard = well.SIMCard;// txtSIMCard.Text;

            src.MonitorTime = DateTime.Parse(txtMonitorTime.Text);
            src.Waterlevel = Convert.ToDecimal(txtWaterlevel.Text);
            src.CellVoltage = txtCellVoltage.Text;
            src.OriginalWaterLevel = txtOriginalWaterLevel.Text;

            if (txtFlowRate.Text.Length > 0)
            {
                src.FlowRate = Convert.ToDecimal(txtFlowRate.Text);
            }
            if (txtHydraulicPressure.Text.Length > 0)
            {
                src.HydraulicPressure = Convert.ToDecimal(txtHydraulicPressure.Text);
            }

            src.WaterQuality = txtWaterQuality.Text;

            if (this.hidMonitorTime.Value.Length == 0)
            {
                src.Table.Rows.Add(src);
            }
            else
            {

            }

            return src.Table.DataSet as MonitoringDataSet;
        }

        private MonitoringDataSet GetFields(string wellCode, string monitorTime)
        {
            MonitoringRow src = null;

            WellRow well = GroundWater.BusinessActions.Well.GetById(wellCode, false);

            if (this.hidMonitorTime.Value.Length == 0)//String.IsNullOrEmpty(wellCode)
            {
                MonitoringRow row = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, DateTime.Parse(txtMonitorTime.Text));
                if (row != null)
                {
                    return null;
                }

                src = (new MonitoringDataSet()).Monitoring.NewMonitoringRow();
                //src.Id = Guid.NewGuid();
                src.Id = Guid.NewGuid().ToByteArray();
                src.WellCode = "";
                src.WellName = "";
                src.BTUAddress = "";
                src.CellVoltage = "";
                src.FlowRate = 0m;
                src.HydraulicPressure = 0m;
                src.MonitorTime = DateTime.Parse("1900-01-01");
                src.OriginalWaterLevel = "";
                src.SectionPlane = "";
                src.SIMCard = "";
                src.Waterlevel = 0m;
                src.WaterQuality = "";
            }
            else
            {
                // update
                src = GroundWater.BusinessActions.Monitoring.FetchById(wellCode, DateTime.Parse(monitorTime));
            }
            src.WellCode = well.Code; //txtCode.Text;
            src.WellName = well.Name;// drpWells.SelectedItem.Text;//txtName.Text;
            src.SectionPlane = well.SectionPlane;// txtSectionPlane.Text;
            src.BTUAddress = well.BTUAddress;// txtBTUAddress.Text;
            src.SIMCard = well.SIMCard;// txtSIMCard.Text;

            src.MonitorTime = DateTime.Parse(txtMonitorTime.Text);
            src.Waterlevel = Convert.ToDecimal(txtWaterlevel.Text);
            src.CellVoltage = txtCellVoltage.Text;
            src.OriginalWaterLevel = txtOriginalWaterLevel.Text;

            if (txtFlowRate.Text.Length > 0)
            {
                src.FlowRate = Convert.ToDecimal(txtFlowRate.Text);
            }
            if (txtHydraulicPressure.Text.Length > 0)
            {
                src.HydraulicPressure = Convert.ToDecimal(txtHydraulicPressure.Text);
            }
            
            src.WaterQuality = txtWaterQuality.Text;

            if (this.hidMonitorTime.Value.Length == 0)
            {
                src.Table.Rows.Add(src);
            }
            else
            {

            }

            return src.Table.DataSet as MonitoringDataSet;
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            //txtCode.Enabled = true;

            ClearFields();

            //drpWells.SelectedValue = drpWell.SelectedValue;

            //if (drpWells.SelectedValue != null)
            //{
            //    txtCode.Text = drpWells.SelectedValue;
            //    WellRow well = GroundWater.BusinessActions.Well.GetById(txtCode.Text, false);
            //    txtSectionPlane.Text = well.SectionPlane;
            //    txtSIMCard.Text = well.SIMCard;
            //    txtBTUAddress.Text = well.BTUAddress;

            //}
            //drpWells.Attributes.Add("onchange", "setFiedls(this);");
            
            WellRow well = GroundWater.BusinessActions.Well.GetById(drpWell.SelectedValue, false);

            txtName.Text = well.Name;
            txtCode.Text = well.Code;
            txtSectionPlane.Text = well.SectionPlane;
            txtSIMCard.Text = well.SIMCard;
            txtBTUAddress.Text = well.BTUAddress;

            this.hidAltitude.Value = well.Depth.ToString();

            txtMonitorTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm");


            SetDisable();
            mdlPopup.Show();
        }

        private void SetDisable()
        {
            txtCode.Enabled = false;
            txtName.Enabled = false;
            txtBTUAddress.Enabled = false;
            txtSectionPlane.Enabled = false;
            txtSIMCard.Enabled = false;
            txtOriginalWaterLevel.Enabled = false;
        }
    }
}
